import 'package:flutter/material.dart';
import 'package:kq_flutter_core_widget/utils/kq_screen_util.dart';
import 'package:get/get.dart';
import 'package:kq_flutter_widgets/widgets/searchBar/kq_search_bar.dart';
import 'package:kq_flutter_widgets/widgets/titleBar/kq_title_bar.dart';
import '../../../config/kq_global.dart';
import '../../../resources/images.dart';
import '../../../resources/kq_theme_colors.dart';
import '../../../widgets/sectionListView/kq_section_list_view.dart';
import 'address_pick_controller.dart';

/// 梁金贝
///
/// 地址选择
class AddressPick extends StatefulWidget {
  const AddressPick({super.key, this.onSelectAddress});

  /// 地址选择block
  final Function(List selectAddressAry)? onSelectAddress;

  @override
  State<AddressPick> createState() => AddressPickState();
}

class AddressPickState extends State<AddressPick> {
  AddressPickController controller =
      Get.put<AddressPickController>(AddressPickController());

  @override
  Widget build(BuildContext context) {
    return GetBuilder(
      init: controller,
      builder: (controller) {
        return WillPopScope(
            child: Scaffold(
              appBar: KqHeadBar(
                headTitle: '选择企业地址',
                back: () {
                  if (controller.isInternational) {
                    Get.back(result: []);
                  } else {
                    if (controller.isProvince) {
                      if (controller.isCity) {
                        controller.goBack();
                      } else {
                        controller.goBack();
                      }
                    } else {
                      if (controller.noIsInternational) {
                        Get.back(result: []);
                      } else {
                        controller.isInternational = true;
                        controller.isSearch = false;
                        controller.editingController.text = '';
                        controller.update();
                      }
                      // Get.back();
                    }
                  }
                },
              ),
              body: controller.isInternational
                  ? firstView(context, controller)
                  : Column(
                      children: [
                        KqSearchBar(
                          editController: controller.editingController,
                          onCancel: () {
                            controller.isSearch = false;
                            controller.update();
                          },
                          onChanged: (value) {
                            if (value == '') {
                              controller.handleClear();
                            } else {
                              controller.isSearch = true;
                              if (controller.inlandSelect) {
                                controller.getSearchForData(value);
                              } else {
                                controller.getSearchForDataInternational(value);
                              }
                            }
                          },
                          onSubmit: (value, KqSearchBarState state) {
                            if (value == '') {
                              controller.handleClear();
                            } else {
                              controller.isSearch = true;
                              if (controller.inlandSelect) {
                                controller.getSearchForData(value);
                              } else {
                                controller.getSearchForDataInternational(value);
                              }
                            }
                          },
                        ),
                        Container(
                          height: 1.r,
                          color: const Color(0xFFf4f4f5),
                        ),
                        controller.inlandSelect
                            ? selectTopView(context, controller)
                            : Container(),
                        (controller.isSearch && controller.searchData.isEmpty)
                            ? Expanded(
                                child: Container(
                                alignment: Alignment.topLeft,
                                padding: EdgeInsets.only(top: 12.r, left: 16.r),
                                child: const Text(
                                  '暂无数据',
                                  textAlign: TextAlign.start,
                                  style: TextStyle(
                                    fontSize: 12,
                                    color: KqThemeColors.text26,
                                  ),
                                ),
                              ))
                            : Expanded(
                                child: controller.isSearch
                                    ? ListView.builder(
                                        itemCount: controller.searchData.length,
                                        itemBuilder: (context, index) {
                                          return Container(
                                            color: const Color(0xFFf4f4f5),
                                            padding: EdgeInsets.only(top: 1.r),
                                            child: renderCell(
                                                context, 0, index, controller),
                                          );
                                        })
                                    : KqSectionListView(
                                        section: controller.dataSource.length,
                                        isSameHeight: true,
                                        isFixTop: true,
                                        rowHeight: ((section) {
                                          return 44.r;
                                        }),
                                        isShowIndex: !controller.isSearch,
                                        indexHeight: 26.r,
                                        indexTextColor:
                                            KqThemeColors.textLightBlue,
                                        indexList: controller.indexList,
                                        headerBuilder: ((section) {
                                          return renderHeader(
                                              section, controller);
                                        }),
                                        itemBuilder: ((section, row, object) {
                                          return Container(
                                            color: const Color(0xFFf4f4f5),
                                            padding: EdgeInsets.only(top: 1.r),
                                            child: renderCell(context, section,
                                                row, controller),
                                          );
                                        }),
                                        itemList: ((section) {
                                          return controller.dataSource[section];
                                        }))),
                      ],
                    ),
            ),
            onWillPop: () async {
              Get.back(result: []);
              return false;
            });
      },
    );
  }
}

Widget firstView(BuildContext context, AddressPickController controller) {
  return Container(
    color: const Color(0xFFf4f4f5),
    child: ListView.builder(
        itemCount: controller.firstData.length,
        itemBuilder: (context, index) {
          return Container(
            color: const Color(0xFFf4f4f5),
            padding: EdgeInsets.only(top: 1.r),
            child: SizedBox(
                height: 44.r,
                child: Container(
                  padding: EdgeInsets.only(left: 16.r, right: 16.r),
                  color: Colors.white,
                  child: InkWell(
                    onTap: () {
                      controller.isInternational = false;
                      if (index == 0) {
                        controller.inlandSelect = true;
                        controller.loadAddressDataApi();
                      } else if (index == 1) {
                        controller.inlandSelect = false;
                        controller.loadInternationalData();
                      }
                    },
                    child: Row(
                      children: [
                        Expanded(
                            child: Text(
                          controller.firstData[index],
                          style: TextStyle(
                            fontSize: 14.r,
                            color: KqThemeColors.text26,
                          ),
                        )),
                        Image.asset(
                          Images.commonIcJiantouRight16,
                          width: 20.r,
                          height: 20.r,
                          package: KqGlobal.packageName,
                        )
                      ],
                    ),
                  ),
                )),
          );
        }),
  );
}

Widget selectTopView(BuildContext context, AddressPickController controller) {
  return Container(
      height: 44.r,
      color: Colors.white,
      child: Row(children: [
        Row(
          children: controller.selectAddressAry
              .asMap()
              .keys
              .map((index) => warpViewCell(controller, index))
              .toList(),
        ),
        const SizedBox(width: 16),
        Text(
          '请选择',
          style: TextStyle(
            fontSize: 14.r,
            color: const Color(0xFF40A9FF),
          ),
        ),
      ]));
}

Widget renderCell(BuildContext context, int section, int row,
    AddressPickController controller) {
  dynamic model;
  if (controller.isSearch) {
    model = controller.searchData[row];
  } else {
    List sectionAry = controller.dataSource[section];
    model = sectionAry[row];
  }
  return Container(
    padding: EdgeInsets.only(left: 16.r, top: 10.r),
    color: Colors.white,
    height: 44.r,
    child: InkWell(
      onTap: () {
        if (controller.isSearch) {
          if (controller.inlandSelect) {
            controller.clickCellSearchMethod(model);
          } else {
            controller.selectAddressAry.add(model.name);
            Get.back(result: controller.selectAddressAry);
          }
        } else {
          if (controller.inlandSelect) {
            controller.clickCellMethod(model);
          } else {
            controller.selectAddressAry.add(model.name);
            Get.back(result: controller.selectAddressAry);
          }
        }
      },
      child: Text(
        model.name,
        style: TextStyle(
          fontSize: 16.r,
          color: KqThemeColors.text26,
        ),
      ),
    ),
  );
}

Widget warpViewCell(AddressPickController controller, int index) {
  return Container(
    padding: EdgeInsets.only(left: 16.r),
    child: Text(
      controller.selectAddressAry[index],
      style: TextStyle(
        fontSize: 14.r,
        color: KqThemeColors.text26,
      ),
    ),
  );
}

Widget renderHeader(int section, AddressPickController controller) {
  String key = controller.indexList[section];
  return Container(
    height: 28.r,
    padding: EdgeInsets.symmetric(horizontal: 16.r),
    alignment: Alignment.centerLeft,
    color: KqThemeColors.bgF4,
    child: Text(
      key,
      maxLines: 1,
      style: TextStyle(fontSize: 16.sp, color: KqThemeColors.text59),
    ),
  );
}
